package com.rslai.base.tool.autotest.mock;

import com.rslai.base.tool.autotest.mock.model.Expectation;
import com.rslai.base.tool.autotest.mock.util.HttpUtil;
import com.rslai.base.tool.autotest.mock.util.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExpectationBuilder {
    private static final Logger logger = LoggerFactory.getLogger(ExpectationBuilder.class);
    private String source;
    private String productNo;
    private String api;
    private String key;
    private String server;

    public ExpectationBuilder(String api) {
        this.api = api;
    }

    public ExpectationBuilder withKey(String key) {
        this.key = key;
        return this;
    }

    public ExpectationBuilder withSource(String source) {
        this.source = source;
        return this;
    }

    public ExpectationBuilder withProductNo(String productNo) {
        this.productNo = productNo;
        return this;
    }

    public ExpectationBuilder withMockServer(String mockServer) {
        this.server = mockServer;
        return this;
    }

    public void thenReturn(Expectation expectation) {
        expectation.setSource(this.source);
        expectation.setTarget(this.productNo);
        expectation.setApi(this.api);
        expectation.setKey(this.key);
        String expectationString = JSON.toJSONString(expectation);
        String result = HttpUtil.post(String.format("http://%s/set.expectation", new Object[]{this.server}), expectationString);
        validateKey(result);
        logger.debug("设置期望时返回结果：" + result);
    }

    private void validateKey(String result) {
        if (result.startsWith("ERROR")) {
            String actualKey = result.substring(result.indexOf("-"));
            String message = "设置接口的时候发生错误：" + actualKey;
            logger.error(message);
            throw new RuntimeException(message);
        }
    }
}
